package jack.com.servicekeep;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.bugly.beta.Beta;

import jack.com.servicekeep.service.GetUnlockCodeResponseData;
import jack.com.servicekeep.service.KeepAliveJobSchedulerService;
import jack.com.servicekeep.service.NoticeResponseData;
import jack.com.servicekeep.service.SmsObserver;
import jack.com.servicekeep.service.WeakRefHandler;
import jack.com.servicekeep.utils.AppUtil;
import jack.com.servicekeep.utils.ShellUtils;
import jack.com.servicekeep.utils.SystemUtil;

public class MainActivity extends Activity implements View.OnClickListener, View.OnLongClickListener {

    private Button btCopy, btQuit, btSetting;

    private TextView tvPhoneId, tvNoticeContent, tvVersion, tvScrollMsg, tvDelayDay, tvDelayCount;
    private TextView tvClassName, tvLearnDay;
    private TextView btCommit, btStartLearnBtn, btSet4G;
    private View btSetWifi;

    private EditText etInputCode;

    private View viewNotActive, viewActive, viewDelay;

    public static int REQUEST_CODE_OPEN_ACCESSIBILITY = 1;
    public static int REQUEST_CODE_OPEN_FLOATVIEW = 2;
    public static int REQUEST_CODE_QUIT = 3;

    private String mAccount = null;

    private SmsObserver mObserver;

    private Handler.Callback mCallback = new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 100:
                    Log.e("yanjun", "SmsCallback " + msg.obj);
                    sendSms((String) msg.obj);
                    break;
            }
            return true;
        }
    };
    private Handler mHandler = new WeakRefHandler(mCallback);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.e("yanjun", "MainActivity onCreate " + this);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS, Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECEIVE_SMS}, 1);
        }

        viewNotActive = findViewById(R.id.view_not_active);
        viewActive = findViewById(R.id.view_active);
        viewDelay = findViewById(R.id.view_delay);

        btStartLearnBtn = findViewById(R.id.start_learn);
        btStartLearnBtn.setOnClickListener(this);

        btCommit = findViewById(R.id.bt_commit);
        btCommit.setOnClickListener(this);

        btCopy = findViewById(R.id.bt_copy);
        btCopy.setOnClickListener(this);

        btQuit = findViewById(R.id.quit_learn);
        btQuit.setOnClickListener(this);

        btSetWifi = findViewById(R.id.bt_set_wifi);
        btSetWifi.setOnClickListener(this);

        btSet4G = findViewById(R.id.bt_set_4G);
        btSet4G.setOnClickListener(this);

        btSetting = findViewById(R.id.bt_setting);
        btSetting.setOnClickListener(this);

        tvPhoneId = findViewById(R.id.tv_phone_id);
        tvVersion = findViewById(R.id.tv_version);
        tvVersion.setOnLongClickListener(this);
        tvNoticeContent = findViewById(R.id.tv_notice_content);
        tvScrollMsg = findViewById(R.id.tv_scrolling_msg);
        tvDelayDay = findViewById(R.id.tv_delay_day);
        tvDelayCount = findViewById(R.id.tv_delay_count);

        tvClassName = findViewById(R.id.tv_class_name);
        tvLearnDay = findViewById(R.id.tv_learn_day);

        etInputCode = findViewById(R.id.et_input_code);

        setUiView();

        mObserver = new SmsObserver(this, mHandler);
        Uri uri = Uri.parse("content://sms");
        getContentResolver().registerContentObserver(uri, true, mObserver);

//        IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
//        registerReceiver(homeReceiver, homeFilter);
    }

    private void setUiView(){
        tvPhoneId.setText(AppUtil.getDeviceUUID(getApplicationContext()));
        etInputCode.setText("");

        try {
            PackageManager pm = getPackageManager();
            PackageInfo pi = pm.getPackageInfo(this.getPackageName(), 0);
            tvVersion.setText("当前版本号：V" + pi.versionName);
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }

        int dingState = AppUtil.getDingState(getApplicationContext());
        if(dingState == 0){
            viewNotActive.setVisibility(View.VISIBLE);
            viewActive.setVisibility(View.GONE);
        }else{
            viewNotActive.setVisibility(View.GONE);
            viewActive.setVisibility(View.VISIBLE);
        }

        tvScrollMsg.setSelected(true);
    }

    public boolean startFloatingService() {
        boolean flag = Settings.canDrawOverlays(this);
        if (!flag) {
            Toast.makeText(this, "当前无权限，请授权", Toast.LENGTH_SHORT);
            startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), REQUEST_CODE_OPEN_FLOATVIEW);
        }
        return !flag;
    }

    private void getNotice(){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                String phoneId = AppUtil.getDeviceUUID(getApplicationContext());
                String data = AppUtil.getNotice(phoneId);  //45TdlcvrjbqAvtl8M3pA1b
                parseNoticeData(data);
            }
        });
        thread.start();
    }

    public void parseNoticeData(final String jsonStr){
        Log.d("yanjun", "Notice response data:" + jsonStr);

        if(jsonStr.isEmpty()){
            return;
        }

        NoticeResponseData responseData;

        try {
            Gson gson = new Gson();
            responseData = gson.fromJson(jsonStr, NoticeResponseData.class);
        }catch (Exception e){
            Log.e("yanjun", e.toString());
            return;
        }

        final NoticeResponseData data = responseData;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if(data == null)
                    return;

                if(data.getState() >= 200 && data.getState() <= 299){
                    NoticeResponseData.NoticeData noticeData = data.getData();
                    if(noticeData == null)
                        return;

                    AppUtil.setCourseCode(getApplicationContext(), noticeData.getCourse_code());
                    AppUtil.setSchoolName(getApplicationContext(), noticeData.getSchool());

                    mAccount = noticeData.getPhone_number();

                    if(data.getState() == 200){
                        viewDelay.setVisibility(View.VISIBLE);
                        tvClassName.setText(noticeData.getClass_name()+" 班级 "+ noticeData.getName() + " 学员您好");
                        tvLearnDay.setText("您至今已学习" + noticeData.getTotal_learning_time());
                        tvDelayDay.setText(noticeData.getNot_learn_day());
                        tvDelayCount.setText(noticeData.getNot_learn_course_hour());
                    }else{
                        viewDelay.setVisibility(View.GONE);
                    }

                    tvScrollMsg.setText(noticeData.getScrolling_msg());
                    if(!noticeData.getColor().isEmpty()) {
                        tvScrollMsg.setTextColor(Color.parseColor(noticeData.getColor()));
                    }

                }else{
                    Toast.makeText(getApplicationContext(), jsonStr, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void getUnlockCode(){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                String phoneNumber = AppUtil.getPhoneNumber2(getApplicationContext());
                String phoneId = AppUtil.getDeviceUUID(getApplicationContext());
                String data = AppUtil.getUnlockCode(phoneNumber, phoneId); //17545571821  15603661211
                parseUnlockCodeResponse(data);
            }
        });
        thread.start();
    }

    public void parseUnlockCodeResponse(final String jsonStr){
        Log.d("yanjun", "Unlock response data:" + jsonStr);

        if(jsonStr.isEmpty()){
            return;
        }

        try {
            Gson gson = new Gson();
            GetUnlockCodeResponseData data = gson.fromJson(jsonStr, GetUnlockCodeResponseData.class);
            if(data == null)
                return;

            if(data.getState() == 200 ) {
                GetUnlockCodeResponseData.GetUnlockCodeData unlockData = data.getData();
                if(unlockData != null){
                    String code = unlockData.getActivate_code();
                    if(code != null && !code.isEmpty()){
                        String pwd = AppUtil.getActivityPwd(getApplicationContext());
                        code = code.substring(0, 6);
                        if(pwd.equalsIgnoreCase(code)){
                            AppUtil.saveDingState(getApplicationContext(), 1);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setUiView();
                                    getNotice();
                                }
                            });
                        }
                    }
                }
            }
        }catch (Exception e){
            Log.e("yanjun", e.toString());
            return;
        }
    }

    private void sendSms(final String msg){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                String phoneId = AppUtil.getDeviceUUID(getApplicationContext());
                String data = AppUtil.sendSmsMessage(phoneId, msg);
                Log.d("yanjun", "sendSms response data:" + data);
            }
        });
        thread.start();
    }

    private void doHeartBeat(){
        BatteryManager manager = (BatteryManager) getSystemService(BATTERY_SERVICE);
        final int battery = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

        final String phoneId = AppUtil.getDeviceUUID(getApplicationContext());
        final String phoneNumber = AppUtil.getPhoneNumber2(getApplicationContext());

        boolean isPlaying = AppUtil.isPlay(getApplicationContext());
        final int state = isPlaying ? 1 : 0;

        final int phoneState = AppUtil.getDingState(getApplicationContext());

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                String data = AppUtil.heartbeat2(phoneId, state, phoneNumber, battery, phoneState);
                Log.d("yanjun", "Do heartbeat response data:" + data);
                getUnlockCode();
            }
        });
        thread.start();
    }

    @Override
    protected void onStart() {
        Log.e("yanjun", "MainActivity onStart " + this);
        super.onStart();
    }

    @Override
    protected void onResume() {
        Log.e("yanjun", "MainActivity onResume " + this);
        Beta.checkAppUpgrade(false, false);

        int dingState = AppUtil.getDingState(getApplicationContext());
        if(dingState == 0) {
            btCommit.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initSettings();
                }
            }, 700);
        }else{
            getNotice();
        }
        super.onResume();
    }

    private void  initSettings(){
        boolean accessState = AppUtil.isStartAccessibilityServiceEnable(getApplicationContext());
        boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();

        if(accessState == false) {
            Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent, 100);
            Toast.makeText(this, "请先打开：无障碍->钉钉按键精灵", Toast.LENGTH_SHORT).show();
            return;
        }

        if(!haveInstallPermission){
            AppUtil.startInstallPermissionSettingActivity(MainActivity.this);
            return;
        }

        if(AppUtil.getPhoneNumber2(getApplicationContext()).isEmpty()){
            showInputPhoneNumberDialog(false);
            return;
        }

        doHeartBeat();
    }

    @Override
    protected void onPause() {
        Log.e("yanjun", "MainActivity onPause  " + this);
        if(mInputPhoneDialog != null && mInputPhoneDialog.isShowing()){
            mInputPhoneDialog.dismiss();
            mInputPhoneDialog = null;
        }
        super.onPause();
    }

    @Override
    protected void onStop() {
        Log.e("yanjun", "MainActivity onStop " + this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.e("yanjun", "MainActivity onDestroy " + this);
        super.onDestroy();

        getContentResolver().unregisterContentObserver(mObserver);
    }

    @Override
    public void onClick(View view) {
        boolean accessState = AppUtil.isStartAccessibilityServiceEnable(getApplicationContext());
        boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
        int dingState = AppUtil.getDingState(getApplicationContext());
        switch (view.getId()) {
            case R.id.start_learn:
                if(accessState == false) {
                    Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivityForResult(intent, REQUEST_CODE_OPEN_ACCESSIBILITY);
                    Toast.makeText(this, "请先打开：无障碍->钉钉按键精灵", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(!haveInstallPermission){
                    AppUtil.startInstallPermissionSettingActivity(MainActivity.this);
                    return;
                }

                if(dingState == 1 && startFloatingService()){
                    return;
                }

                if(AppUtil.getAllowLearnState(getApplicationContext()) == false){
                    Toast.makeText(this, "今日学习时长已达到上限，请明天继续!", Toast.LENGTH_SHORT).show();
                    return;
                }

                enterDing();
                break;
            case R.id.bt_commit:

                if(accessState == false) {
                    Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivityForResult(intent, REQUEST_CODE_OPEN_ACCESSIBILITY);
                    Toast.makeText(this, "请先打开：无障碍->钉钉按键精灵", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(!haveInstallPermission){
                    AppUtil.startInstallPermissionSettingActivity(MainActivity.this);
                    return;
                }

                String input = etInputCode.getText().toString();
                if(input.isEmpty()){
                    Toast.makeText(this, "请输入激活码", Toast.LENGTH_SHORT).show();
                    return;
                }
                String pwd = AppUtil.getActivityPwd(getApplicationContext());
                Log.d("yanjun", "Activity: pwd="+pwd + " input="+input);
                if(pwd.equalsIgnoreCase(input)){
                    AppUtil.saveDingState(getApplicationContext(), 1);
                    //Toast.makeText(this, "激活成功，请点击“开始学习”", Toast.LENGTH_SHORT).show();
                    AppUtil.hideInput(this);
                    setUiView();
                    getNotice();
                }else{
                    Toast.makeText(this, "无效激活码", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.bt_copy:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData mClipData = ClipData.newPlainText("PhoneId", tvPhoneId.getText());
                cm.setPrimaryClip(mClipData);

                Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.quit_learn:
                startActivityForResult(new Intent(MainActivity.this, QuitActivity.class), REQUEST_CODE_QUIT);
                break;
            case R.id.bt_set_wifi:
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                break;
            case R.id.bt_set_4G:
                startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
                break;
            case R.id.bt_setting:
                if(AppUtil.getMenuState(getApplicationContext()) == 0) {
                    showPopupMenuNotActive();
                }else {
                    showPopupMenu();
                }
                break;
        }
    }

    @Override
    public boolean onLongClick(View view) {
        if(view.getId() == R.id.tv_version){
            AppUtil.setMenuState(getApplicationContext(), 0);
        }
        return true;
    }

    private void enterDing(){
        AppUtil.setPunchClockState(this, 1);
        AppUtil.setMenuState(this, 1);
        KeepAliveJobSchedulerService.openDing(this);
    }

    private Dialog mInputPhoneDialog;
    private void showInputPhoneNumberDialog(final boolean cancelable){
        if(mInputPhoneDialog == null) {
            final EditText inputServer = new EditText(this);
            inputServer.setInputType(InputType.TYPE_CLASS_PHONE);
            inputServer.setHint("请务必输入11位正确的手机号");
            inputServer.setText(AppUtil.getPhoneNumber2(getApplicationContext()));
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("请输入本机手机号").setView(inputServer);
            //builder.setNegativeButton("取消", null);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    String text = inputServer.getText().toString().trim();
                    Log.d("yanjun", "Input " + inputServer.getText().toString());
                    if (text.length() == 11) {
                        AppUtil.savePhoneNumber(getApplicationContext(), text);
                        if(AppUtil.getDingState(getApplicationContext()) == 0 ) {
                            doHeartBeat();
                        }
                    } else {
                        mInputPhoneDialog = null;
                        showInputPhoneNumberDialog(cancelable);
                        Toast.makeText(MainActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();

                    }
                }
            });
            builder.setCancelable(cancelable);
            mInputPhoneDialog = builder.create();
        }
        mInputPhoneDialog.show();
    }

    private void showPopupMenuNotActive(){
        PopupMenu popupMenu = new PopupMenu(this, btSetting);
        if(SystemUtil.getSystemModel().equals("AUM-AL20")){
            popupMenu.inflate(R.menu.menu_not_active);
        }else{
            popupMenu.inflate(R.menu.menu_not_active_no_setting);
        }
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.set_wifi:
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                        return true;
                    case R.id.set_4G:
                        startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
                        return true;
                    case R.id.download_ding:
                        String url = "http://download.alicdn.com/wireless/dingtalk/latest/rimet_700219.apk";
                        AppUtil.openBrowser(MainActivity.this, url);
                        return true;
                    case R.id.set_ding_install:
                        if(!AppUtil.isAppInstalled(getApplicationContext(), "com.alibaba.android.rimet")){
                            Toast.makeText(MainActivity.this, "请先安装钉钉", Toast.LENGTH_SHORT).show();
                            return true;
                        }
                        AppUtil.startInstallPermissionSettingActivityDing(MainActivity.this);
                        return true;
                    case R.id.set_phone_number:
                        showInputPhoneNumberDialog(true);
                        return true;
                    case R.id.auto_setting:
                        if(!AppUtil.isAppInstalled(getApplicationContext(), "com.alibaba.android.rimet")){
                            Toast.makeText(MainActivity.this, "请先安装钉钉", Toast.LENGTH_SHORT).show();
                            return true;
                        }
                        boolean accessState = AppUtil.isStartAccessibilityServiceEnable(getApplicationContext());
                        if(accessState == false) {
                            Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivityForResult(intent, REQUEST_CODE_OPEN_ACCESSIBILITY);
                            Toast.makeText(MainActivity.this, "请先打开：无障碍->钉钉按键精灵", Toast.LENGTH_SHORT).show();
                            return true;
                        }
                        AppUtil.setAutoSettingsStart(getApplicationContext(), 1);
                        AppUtil.setAutoSettingsFlag(getApplicationContext(), 1);
                        startActivity(new Intent(Settings.ACTION_SETTINGS));
                        return true;
                    default:
                        //do nothing
                }
                return false;
            }
        });
        popupMenu.show();
    }

    private void showPopupMenu(){
        PopupMenu popupMenu = new PopupMenu(this, btSetting);
        popupMenu.inflate(R.menu.menu_setting);
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.set_wifi:
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                        return true;
                    case R.id.set_4G:
                        startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
                        return true;
                    case R.id.clean_ding:
                        openDingClean();
                        return true;
                    case R.id.update_ding:
                        AppUtil.setUpdateDingState(MainActivity.this, 1);
                        enterDing();
                        return true;
                    case R.id.search_account:
                        if(mAccount == null) {
                            Toast.makeText(MainActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
                        }else{
                            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
                            dialogBuilder.setTitle("账号查询");
                            dialogBuilder.setMessage("您的钉钉账号为:" + mAccount);
                            dialogBuilder.setPositiveButton("知道了", null);
                            final AlertDialog alertDialog = dialogBuilder.create();
                            alertDialog.show();
                        }
                        return true;
                    case R.id.set_phone_number:
                        showInputPhoneNumberDialog(true);
                        return true;
                    default:
                        //do nothing
                }
                return false;
            }
        });
        popupMenu.show();
    }

    private void uuidTest(){
        for(int i = 0; i<10; i++) {
            Log.d("yanjun", "short:" + AppUtil.getShortUuid22());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("yanjun", "keyCode:"+ keyCode + " event="+event);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("yanjun", "requestCode:"+ requestCode + " resultCode="+resultCode +  " data=" + data);

        if(requestCode == REQUEST_CODE_OPEN_ACCESSIBILITY){
            boolean state = AppUtil.isStartAccessibilityServiceEnable(getApplicationContext());
            Log.d("yanjun", "state:"+state);

            if(state == true){
                KeepAliveJobSchedulerService.openDing(this);
            }
        }else if(requestCode == REQUEST_CODE_QUIT){
            if(resultCode == RESULT_OK){
                ;//toSelfSetting(this);
            }
        }
    }

    private void open2(){
//        ShellUtils.CommandResult result =  ShellUtils.execCommand("settings put secure enabled_accessibility_services jack.com.servicekeep/jack.com.servicekeep.service.MyAccessibilityService",
//                false, true);

        String [] commands = new String[1];
        commands[0] = "settings put secure accessibility_enabled 1 ";
        //commands[1] = "ls";

        ShellUtils.CommandResult result =  ShellUtils.execCommand(commands,
                false, true);

        Log.d("yanjun", "execCommand" + result.toString());
    }

    // Just for have system app
    private void open(){
        Settings.Secure.putString(getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                "jack.com.servicekeep/jack.com.servicekeep.service.MyAccessibilityService");

        Settings.Secure.putInt(getContentResolver(),
                Settings.Secure.ACCESSIBILITY_ENABLED, 1);
    }

    private void openLauncherSelectDialog(){

        Intent  paramIntent = new Intent("android.intent.action.MAIN");
        paramIntent.setComponent(new ComponentName("com.huawei.android.internal.app", "com.huawei.android.internal.app.HwResolverActivity"));
        paramIntent.addCategory("android.intent.category.DEFAULT");
        paramIntent.addCategory("android.intent.category.HOME");
        startActivity(paramIntent);
    }

    private void openDingClean(){
        ComponentName componentName = new ComponentName("com.huawei.systemmanager",
                "com.huawei.systemmanager.spacecleanner.SpaceCleanActivity");//这里是 包名  以及 页面类的全称
        Intent intent = new Intent();
        intent.setComponent(componentName);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private final BroadcastReceiver homeReceiver = new BroadcastReceiver() {
        final String SYS_KEY = "reason"; // 标注下这里必须是这么一个字符串值

        final String SYS_HOME_KEY = "homekey";// 标注下这里必须是这么一个字符串值

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYS_KEY);
                if (reason != null && reason.equals(SYS_HOME_KEY)) {
                    Log.i("yanjun", "##################home键监听");
                    Toast.makeText(MainActivity.this, "aaaa",
                            Toast.LENGTH_SHORT).show();

                    openLauncherSelectDialog();
                }
            }
        }
    };

    private void changeLauncer(Context context){
        PackageManager pm = context.getPackageManager();
        ComponentName component = new ComponentName(
                context.getPackageName(), MainActivity.class.getName());//红色为自己的launcher入口
        ComponentName[] components = new ComponentName[] {
                new ComponentName("com.android.launcher",
                        "com.android.launcher2.Launcher"), component };
        pm.clearPackagePreferredActivities("com.android.launcher");//清除默认launcher
        //pm.addPreferredActivity(filter, IntentFilter.MATCH_CATEGORY_EMPTY,
         //       components, component);
    }

    public static void toSelfSetting(Context context) {
        Intent mIntent = new Intent();
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            mIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.setAction(Intent.ACTION_VIEW);
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            mIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(mIntent);
    }

}
